package com.easycode.devtool.util;

import com.google.common.collect.Maps;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;

/**
 *
 * 用户请求的详细解析类
 */
final public class RequestUtils
{

    /**
     * 获取multipart/form-data 格式的数据
     * @param request
     * @return
     */

    public static String getMultipartDataFromRequest(HttpServletRequest request){
        try{
            BufferedReader reader = request.getReader();
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = reader.readLine()) != null)
                stringBuffer.append(line);
            return stringBuffer.toString();
        }catch(Exception e){

            e.printStackTrace();
        }
        return "";
    }

//    /**
//     * 获取文件格式数据
//     * @param request
//     * @return
//     */
//
//    public static Map<String,String> getParamsMap(HttpServletRequest request) {
//
//        Map<String,String> paramsMap = Maps.newHashMap();
//
//        try {
//            DiskFileItemFactory fac = new DiskFileItemFactory();
//            ServletFileUpload upload = new ServletFileUpload(fac);
//            upload.setHeaderEncoding("utf-8");
//            List fileList = null;
//            fileList = upload.parseRequest(request);
//
//            if(null == fileList || fileList.isEmpty())
//            {
//                return  paramsMap;
//            }
//            Iterator<FileItem> it = fileList.iterator();
//            while (it.hasNext()) {
//                FileItem item = it.next();
//                if (item.isFormField()) {
//                    String fieldName = item.getFieldName();
//                    String fieldValue = item.getString();
//                    paramsMap.put(fieldName,fieldValue);
//                    item.delete();  //释放输出流
//                }
//            }
//
//        } catch (FileUploadException e) {
//            e.printStackTrace();
//        }
//
//
//        return  paramsMap;
//    }


    public static String getInputDataFromRequest(HttpServletRequest request) {
     return     getJsonDataFromRequest(request,"UTF-8");
    }
    /**
     * 针对提交数据为post格式，而且是JSON数据流的提交信息，进行JSON解析
     * 注意：仅仅能获取一次
     *
     * @param request
     * @return
     */
    public static String getJsonDataFromRequest(HttpServletRequest request)
    {

        return getJsonDataFromRequest(request,"UTF-8");
    }

    /**
     * 针对提交数据为post格式，而且是JSON数据流的提交信息，进行JSON解析
     * 注意：仅仅能获取一次
     *
     * @param request
     * @return
     */
    public static String getJsonDataFromRequest(HttpServletRequest request, String encodeText)
    {
        BufferedReader br = null;
        StringBuilder sbf = new StringBuilder();
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), encodeText));
            String line = "";
            while ( StringUtils.isNotEmpty((line = br.readLine())))
            {
                sbf.append(line);
            }
            if(sbf.length()>0)
            {
                byte[] bytes = sbf.toString().getBytes(encodeText);
                String jsonStr = new String(bytes,encodeText);
                return jsonStr;
            }

            //如果通过流读取的方式获取不到参数，采用普通的方式获取参数

             Map<String,String> paramsMap = getMapFromRequest(request);

            if(CollectionUtils.isNotNullOrEmpty(paramsMap))
            {
                return  JsonUtils.getJson(paramsMap);
            }


        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(null!=br){
                try {
                    br.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * 得到用户的请求来源地址
     * @return
     */
    public static String getIp(HttpServletRequest request)
    {
        return IPUtils.getIp(request);
    }

    /**
     * 功能：获取请求来源页
     * @param request
     * @return
     */
    public static String getReferrer(HttpServletRequest request)
    {
        return request.getHeader("referer");
    }


    /**
     * 获取请求参数，不包括空值参数
     * @param request
     * @return
     */
    public static Map<String, String> getMapFromRequest(HttpServletRequest request)
    {
        return  getMapFromRequest(request,true);
    }

    public static Map<String, String> getMapFromRequestIncludeNullParam(HttpServletRequest request)
    {
        return  getMapFromRequest(request,true);
    }

    /**
     * 从请求对象中提取参数到map
     * @param request   请求对象
     * @return          参数map
     */
    private static Map<String, String> getMapFromRequest(HttpServletRequest request, boolean keepNullOrEmptyParam)
    {
        Map<String, String[]> requestMap = request.getParameterMap();
        System.out.println("这个Map对象的长度是"+requestMap.size());
        if (requestMap.isEmpty())  return null;

        //创建先对象，过滤特定记录内容
        Map<String, String> paramsMap = Maps.newHashMap();
        for (String key : requestMap.keySet())
        {
            System.out.println("这是map对象(key)的键，键值为"+key);
            String[] valueArray = requestMap.get(key);
            String value = "" ;

            if( null != valueArray &&  0 < valueArray.length )
            {
                value  = valueArray[0];
            }

            System.out.println("这是map对象(value)的值 值为+"+value);

            if (StringUtils.isNotEmpty(value))
            {
                paramsMap.put(key,value);
            }else{
                if(keepNullOrEmptyParam)
                {
                    paramsMap.put(key,value);
                }
            }
        }

        return paramsMap;
    }

    /**
     * 获取请求过来的参数信息(兼容post,get两种方式)
     * @return
     */
    public static  String getMapStringFromRequest(HttpServletRequest request)
    {
        return getMapStringFromRequest(request,true);
    }

    /**
     * 获取请求过来的参数信息(兼容post,get两种方式)
     * @return
     */
    public static  String getMapStringFromRequest(HttpServletRequest request, boolean isIncludeMethod)
    {
        Map<String, String[]> params = request.getParameterMap();
        StringBuffer sb = new StringBuffer(32);

        //判断是否添加当前请求类型
        if(isIncludeMethod)
        {
            sb.append(request.getMethod() + " ");
    }
        for (String key : params.keySet())
        {
            String[] values = params.get(key);
            for (int i = 0; i < values.length; i++)
            {
                String value = values[i];
                sb.append( key + "=" + value + "&");
            }
        }

        //返回结果信息
        return sb.toString().substring(0, sb.length() - 1);
    }


    /**
     * 功能：得到完整的请求地址，包含域名
     * @param request
     * @return
     */
    public static String getUrl(HttpServletRequest request)
    {
        return getUrl(request,true,true);
    }
    public static String getUrl(HttpServletRequest request, boolean isGetParam, boolean isIncludeDomain)
    {
        StringBuilder sb = new StringBuilder(50);


            //判断是否需要完整域名的地址
            if (isIncludeDomain) {
                sb.append(request.getRequestURL());

                //System.out.println("完整地址:" + isIncludeDomain + " " + request.getRequestURL());
            } else {
                sb.append(request.getRequestURI());

                //System.out.println("简单地址:" + isIncludeDomain + " " + request.getRequestURI());
            }


        //判断是否需要参数
        String queryString = request.getQueryString();
        if(!StringUtils.isEmpty(queryString))
        {
            if (isGetParam) {
                sb.append("?");
                sb.append(queryString);
            }
        }
        return sb.toString();
    }

    /**
     * 功能：获取客户端的用户基本信息
     * @param request
     * @return
     */
    public static String getUserAgent(HttpServletRequest request)
    {
        String  s = request.getHeader("User-Agent");

        return s;
    }


    /**
     * 得到当前手机的类型，主要是区分IOS，还是Android
     * @param request
     * @return
     */
    public static String getMobileOs(HttpServletRequest request)
    {
        String osVersion = "Android";
        String  s = getUserAgent(request);

        if (s.contains("iPhone"))
        {
            osVersion = "iPhone";
        }
        else if (s.contains("iPad"))
        {
            osVersion = "iPad";
        }
        else if (s.contains("Mac"))
        {
            osVersion = "Mac";
        }
        else if (s.contains("Safari"))
        {
            osVersion = "IOS";
        }

        return osVersion;
    }

    /**
     * 功能：获取用户操作系统信息
     * @param userAgent
     * @return
     */
    public static String getOSNameByUserAgent(String userAgent)
    {
        String osVersion = "未知";

        if (userAgent.contains("NT 6.0"))
        {
            osVersion = "Windows Vista/Server 2008";
        }
        else if (userAgent.contains("NT 5.2"))
        {
            osVersion = "Windows Server 2003";
        }
        else if (userAgent.contains("NT 5.1"))
        {
            osVersion = "Windows XP";
        }
        else if (userAgent.contains("NT 5"))
        {
            osVersion = "Windows 2000";
        }
        else if (userAgent.contains("NT 4"))
        {
            osVersion = "Windows NT4";
        }
        else if (userAgent.contains("Me"))
        {
            osVersion = "Windows Me";
        }
        else if (userAgent.contains("98"))
        {
            osVersion = "Windows 98";
        }
        else if (userAgent.contains("95"))
        {
            osVersion = "Windows 95";
        }
        else if (userAgent.contains("Mac"))
        {
            osVersion = "Mac";
        }
        else if (userAgent.contains("Unix"))
        {
            osVersion = "UNIX";
        }
        else if (userAgent.contains("Linux"))
        {
            osVersion = "Linux";
        }
        else if (userAgent.contains("SunOS"))
        {
            osVersion = "SunOS";
        }
        else if (userAgent.contains("iPhone"))
        {
            osVersion = "iPhone";
        }
        else if (userAgent.contains("iPad"))
        {
            osVersion = "iPad";
        }
        else if (userAgent.contains("Safari"))
        {
            osVersion = "IOS";
        }



        return osVersion;
    }

//    /**
//     * 页面重定向方法，这个表示，重定向到当前页面
//     */
//    public static ModelAndView redirect(HttpServletRequest request)
//    {
//        return redirect(RequestUtils.getUrl(request));
//    }
//
//    /**
//     * 重定向到特定页面
//     */
//    public static ModelAndView redirect(String url)
//    {
//        return new ModelAndView(
//                new RedirectView(url)
//        );
//    }


    /**
     * 转向到特定地址
     * @param response
     * @param url
     */
    public static void redirect(HttpServletResponse response, String url)
    {
        try {
            response.sendRedirect(url);
        }
        catch (IOException e){;}
        catch (Exception e){;}
    }


    /**
     * 提供接口的jsonp跨域支持；
     * @param response
     * @param s
     * @param request
     */
    public  static  void write(HttpServletResponse response, String s, HttpServletRequest request)
    {
        write(response,s,"utf-8",request);
    }

    public  static  void write(HttpServletResponse response, String s)
    {
        write(response,s,"utf-8");
    }
    public  static  void write(HttpServletResponse response, String s, String textEncoding)
    {
       write(response,s,textEncoding,null);
    }

    public  static  void write(HttpServletResponse response, String s, String textEncoding, HttpServletRequest request)
    {
        //默认支持跨域访问
        response.setContentType("text/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS，DELETE, PUT");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

        //输出结果
        PrintWriter writer = null;
        try {
            response.setHeader("Content-type", "text/html;charset=" + textEncoding);
            writer = response.getWriter();

            //判断是否需要jsonp支持；
            if(null!=request)
            {
                String jsoncallback = request.getParameter("jsoncallback");
                if(StringUtils.isNotEmpty(jsoncallback))
                {
                    s=jsoncallback + "(" +s+")";
                }
            }

            writer.write(s);
        } catch (IOException e)
        {
            //e.printStackTrace();
        }
        finally {
            if(null != writer) writer.close();
        }
    }
}
